<template>
  <span>
    <a-select
      v-model="tag"
      :mode="mode"
      style="min-width: 120px"
      placeholder="请选择"
      option-label-prop="label"
      @change="triggerChange"
    >
      <a-select-option key="egferdgerger" value="" label="全部查询">
        全部查询
      </a-select-option>
      <a-select-option v-for="d in list" :key="d.id" :value="d.code" :label="d.name">
        {{ d.name }}
      </a-select-option>
    </a-select>
  </span>
</template>

<script>
import { getLevelTwoType } from '@/api/basicdata/basictype'

export default {
  props: {
    // value数据从form表单中获取，上层form表单通过装饰器将value传入该组件
    // eslint-disable-next-line vue/require-prop-types
    value: {
      required: true
    },
    typeid: {
      required: true,
      type: String
    },
    pcode: {
      required: true,
      type: String
    },
    mode: {
      default: 'default',
      type: String
    }
  },
  // 将上层的value数据变为1组件内部数据，以便进行双向绑定
  data() {
    // const value = this.mode === 'default' ? this.value || '' : this.value || []
    return {
      tag: JSON.parse(JSON.stringify(this.value)),
      list: []
    }
  },
  watch: {
    value: {
      immediate: true,
      handler: function() {
        if (this.value === '') {
          console.log('reset')
          this.tag = JSON.parse(JSON.stringify(this.value))
        }
      }
    }
  },
  mounted() {
    console.log(this.tag)
    const data = {
      'searchParams': { 'typeId': this.typeid,
        'pcode': this.pcode
      }
    }
    getLevelTwoType(data).then(res => {
      this.list = res.responseBody.result
    })
  },
  methods: {
    triggerChange(changedValue) {
      // this.$emit('input', changedValue)
      // const event = { target: {
      //   value: ''
      // }}
      console.log('changedValue')
      console.log(changedValue)
      const listtar = [...this.list]
      // 后端定义好后，传后端所需要的值到表单中
      if (this.mode !== 'default') {
        const data = []
        changedValue.forEach(element => {
          const res = listtar.filter(item => element === item.code)[0]
          data.push({
            name: res.name,
            code: res.code
          })
        })
        // 触发change事件，使得组件数据可以被上层form表单接收
        event.target.value = data
        console.log(data)
        this.$emit('input', data)
      } else {
        const data = listtar.filter(item => changedValue === item.code)[0]
        event.target.value = data
        console.log(data)
        if (changedValue !== '') {
          this.$emit('input', {
            name: data.name,
            code: data.code
          })
        } else {
          this.$emit('input', '')
        }
      }
    }
  }
}
</script>
